<?php

namespace App\Http\Requests\Admin\Customer\Product;

use App\Http\Requests\ApiRequest;
use App\Models\Panx\Brand;
use App\Models\Panx\BrandSeries;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\Guard;

/**
 * @property string product_id
 * @property string|null brand_id
 * @property string|null brand_series_id
 */
class ShareProductStoreRequest extends ApiRequest
{
    use ApiChecker;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        $this->validateBrandAndSeries();

        return [
            'product_id'      => 'required|int|min:1',
            'brand_id'        => 'nullable|required_with:brand_series_id|int|min:1',
            'brand_series_id' => 'nullable|int|min:1',
        ];
    }

    private function validateBrandAndSeries()
    {
        if ((int) $this->brand_id !== 0) {
            $this->validateCustomerHasBrand();

            if ((int) $this->brand_series_id !== 0) {
                $this->validateCustomerHasBrandSeries();
            }
        }
    }

    private function validateCustomerHasBrand(): void
    {
        $id = $this->brand_id;

        $has_brand = (new Brand)
            ->where('customer_id', Guard::customer()->id ?? null)
            ->whereKey($id)
            ->exists();

        $this->checkParamError($has_brand, "brand id: $id not belongs to current customer");
    }

    private function validateCustomerHasBrandSeries(): void
    {
        $id = $this->brand_series_id;

        $has_brand_series = (new BrandSeries)
            ->where('customer_id', Guard::customer()->id ?? null)
            ->where('brand_id', $this->brand_id)
            ->whereKey($id)
            ->exists();

        $this->checkParamError($has_brand_series, "brand series id: $id not belongs to current customer");
    }
}
